package com.hillky.serialize.impl;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.hillky.exceptions.SerializeException;
import com.hillky.serialize.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

@Slf4j
public class HessianSerializer implements Serializer {
    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return null;
        }

        try (
                // 将流的定义写在try里面，会自动关闭IO流，不需要再写final
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ){
            Hessian2Output hessian2Output = new Hessian2Output(baos);
            hessian2Output.writeObject(object);
            hessian2Output.flush();

            byte[] result = baos.toByteArray();
            if(log.isDebugEnabled()){
                log.debug("对象【{}】Hessian序列化已经完成,长度是【{}】",object,result.length);
            }
            return result;
        } catch (IOException e) {
            log.error("使用Hessian序列化对象时发生异常",object);
            throw new SerializeException();
        }

    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null||clazz==null) {
            return null;
        }

        try (
                // 将流的定义写在try里面，会自动关闭IO流，不需要再写final
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                ) {
            Hessian2Input hessian2Input = new Hessian2Input(bais);
            T  object = (T) hessian2Input.readObject();
            if(log.isDebugEnabled()){
                log.debug("类使用Hessian【{}】反序列化已经完成",clazz);
            }
            return object;
        } catch (IOException e) {
            log.error("使用Hessian反序列化对象时发生异常");
            throw new SerializeException();
        }

    }
}
